/**
 * tab 切换
 */
define('utils/Tab', null, function() {

/**
 * new Tab(oldClassName, activeClassName).init(handlers, areas = null)
 */
var Tab = function(oldClassName, activeClassName) {
    this.oldClassName = oldClassName;
    this.activeClassName = activeClassName;
    this.callback = null;
    this.handlers = null;  // Array
    this.showAreas = null;  // Array
};
Tab.prototype = {
    constructor : Tab,
    findHandleIndex: function() {
        var index = -1;

        var len =  this.handlers.length;
        for(var i=0; i<len; i++) {
            if(this.activeClassName === this.handlers[i].className) {
                index = i;
                break;
            }
        }

        return index;
    }
    ,clearAllHandleStyle : function() {
        var len = this.handlers.length;
        for(var i=0; i<len; i++) {
            this.handlers[i].className = this.oldClassName;
        }
    }
    ,closeAllContentAreas : function() {
        if(!this.showAreas) {
            return;
        }

        var len = this.showAreas.length;
        for(var i=0; i<len; i++) {
            this.showAreas[i].style.display = 'none';
        }
    }
    ,openNowContentArea : function() {
        var index = this.findHandleIndex();

        if(-1 === index) {
            return;
        }

        if(this.showAreas) {
            this.showAreas[index].style.display = 'block';
        }
    }
    ,start : function() {
        var _self = this;
        var len = this.handlers.length;

        for(var i=0; i<len; i++) {
            this.handlers[i].onclick = function(e) {
                _self.clearAllHandleStyle();
                _self.closeAllContentAreas();

                this.className = _self.activeClassName;
                _self.openNowContentArea();

                if(null !== _self.callback) {
                    _self.callback(_self.findHandleIndex());
                }
            };
        }
    }
    ,setActiveOf: function(index) {
        this.clearAllHandleStyle();
        this.closeAllContentAreas();

        this.handlers[index].className = this.activeClassName;
        this.openNowContentArea();
    }
    ,init : function(handlers, showAreas) {
        this.handlers = handlers;
        this.showAreas = showAreas;

        this.start();
    }
};

return Tab;

});

